package com.by.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.by.domain.pojo.SysUser;
import com.by.mapper.SysUserMapper;
import com.by.security.LoginUser;
import com.by.service.SysUserService;
import com.by.utils.JwtUtil;
import com.by.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public String login(String username, String password) {
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

        Authentication authenticate = authenticationManager.authenticate(authRequest);


        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }

        // 获取用户信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        // 登录成功 ，创建一个token（身份卡）,jwt
        String token = JwtUtil.createJWT(loginUser.getSysUser().getUserId().toString());

        // 权限信息  要从数据库里查
        List<String> perms = sysUserMapper.findPermsByUserId(loginUser.getSysUser().getUserId());
        loginUser.setPerms(perms);

        // 把登录的用户存到缓存里
        // key的规范，login:id
        redisCache.setCacheObject("login:"+loginUser.getSysUser().getUserId(),loginUser,1, TimeUnit.HOURS);

        return token;
    }

    @Override
    public void logout() {
        // 拿到当前用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        // 从缓存中删除用户
        redisCache.deleteObject("login:"+loginUser.getSysUser().getUserId());
    }

}




